package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    /**
     * 角色分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param roleDto
     * @return
     */
    @Override
    @Cacheable(value = "role:page",key = "#roleDto.hashCode()")
    public PageResponse<RoleVo> page(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        PageHelper.startPage(pageNum,pageSize);
        Page<RoleVo> page = roleMapper.page(role);
        PageResponse<RoleVo> response = PageResponse.of(page, RoleVo.class);
        return response;
    }

    /**
     * 根据角色查询选中的资源数据
     *
     * @param roleId
     * @return
     */
    @Override
    public List<String> findCheckedResources(Long roleId) {

        return roleMapper.findCheckedResources(roleId);
    }

    /**
     * 查询所有角色
     *
     * @return
     */
    @Override
    @Cacheable(value = "role:list")
    public List<RoleVo> selectAll() {
        return roleMapper.selectAll();
    }

    /**
     * 角色修改
     *
     * @param roleDto
     */
    @Override
    @Transactional
    @Caching(evict = {
            @CacheEvict(value = "role:list",allEntries = true),
            @CacheEvict(value = "role:page",allEntries = true)
    })
    public void update(RoleDto roleDto) {
        //根据DataState判定修改类型
        if (roleDto.getDataState() == null){
            //修改菜单列表的对应权限
            //1、先将含有该Id的sys_role_resource表中的对应项删除
            roleMapper.deleteById(roleDto.getId());
            //创建集合进行批量插入进入sys_role_resource表
            List<RoleResource> list = new ArrayList<>();
            Arrays.stream(roleDto.getCheckedResourceNos()).forEach(item->{
                RoleResource roleResource = new RoleResource();
                roleResource.setRoleId(roleDto.getId());
                roleResource.setResourceNo(item);
                roleResource.setDataState(SuperConstant.DATA_STATE_0);
                list.add(roleResource);
            });
            roleResourceMapper.batchInsert(list);
            return;
        }
        //自己的基础信息的更新，包括禁用启用


        Role role = BeanUtil.toBean(roleDto, Role.class);
        if (role.getDataState().equals(SuperConstant.DATA_STATE_1)){
            Integer count =  roleResourceMapper.selectUserByRoleId(roleDto.getId());
            if (count > 0){
                //有关联的员工，不能禁用抛出异常
                throw new BaseException(BasicEnum.NO_DISABLE_USER);
            }
        }
        roleMapper.update(role);
    }

    /**
     * 新增角色
     *
     * @param roleDto
     */
    @Override
    @Caching(evict = {
            @CacheEvict(value = "role:list",allEntries = true),
            @CacheEvict(value = "role:page",allEntries = true)
    })
    public void insert(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    /**
     * 删除角色
     *
     * @param roleIds
     */
    @Override
    @Transactional
    @Caching(evict = {
            @CacheEvict(value = "role:list",allEntries = true),
            @CacheEvict(value = "role:page",allEntries = true)
    })
    public void deleteById(Long roleIds) {

        //查询角色状态
       Role role =  roleMapper.getById(roleIds);
       if (role.getDataState().equals(SuperConstant.DATA_STATE_0)){
           //启用状态无法删除
           throw new BaseException(BasicEnum.NO_DISABLE_DELETE);
       }


        //判断该角色是否对应了职工
        Integer count =  roleResourceMapper.selectUserByRoleId(roleIds);
        if (count > 0){
            //有关联的员工，不能禁用抛出异常
            throw new BaseException(BasicEnum.NO_DISABLE_USER);
        }
        //删除员工信息
        roleMapper.delete(roleIds);
        //删除角色资源关联表
        roleMapper.deleteById(roleIds);
    }
}
